import pymysql.cursors


class ToConn:
    def __init__(self):
        self.connection = pymysql.connect(
            host='localhost',
            user='root',
            password='root',
            db='siheyuanfang',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )

    def get_db(self, sql, t=None):
        """
        执行查询数据库命令
        :param sql: SQL语句
        :param t: 需要替换的元祖tuple
        :return: 查询游标
        """
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql, t)
                return cursor
        # 关闭数据库连接
        finally:
            self.connection.cursor().close()
            self.connection.close()

    def to_execute(self):
        """
        执行execute 语句
        :return: 返回游标
        """
        try:
            return self.connection
        except Exception as e:
            print('===============to_execute===============\n', e)

    def to_db(self, sql, t=None):
        """
        执行操作数据库的命令
        :param sql: SQL语句
        :param t: 需要替换的元祖tuple
        :return: 返回数据库链接对象
        """
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql, t)
                return self.connection
        except Exception as e:
            print('===============to_db===============\n', e)

    def to_close(self):
        """
        关闭链接
        :return:
        """
        self.connection.cursor().close()
        self.connection.close()

